package com.xmb.wcapi.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmb.wcapi.annotation.ValidateJWT;
import com.xmb.wcapi.constant.LayTableR;
import com.xmb.wcapi.constant.MaterialTypeConstant;
import com.xmb.wcapi.constant.R;
import com.xmb.wcapi.dto.ReportDTO;
import com.xmb.wcapi.entity.BaseMaterial;
import com.xmb.wcapi.entity.SysUser;
import com.xmb.wcapi.service.IBaseMaterialService;
import com.xmb.wcapi.service.IDjBaseMaterialService;
import com.xmb.wcapi.util.BeanUtil;
import com.xmb.wcapi.util.Column;
import com.xmb.wcapi.util.ExcelTool;
import com.xmb.wcapi.util.TitleEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-06-14
 */
@Slf4j
@Controller
@RequestMapping("/base_material")
public class BaseMaterialController {

    @Autowired
    IBaseMaterialService baseMaterialService;

    @Autowired
    IDjBaseMaterialService djBaseMaterialService;

    @RequestMapping("/baseIndex")
    public String baseIndex(){
        return "base_material/index";
    }

    @RequestMapping("/djBaseIndex")
    public String djBaseIndex(){
        return "base_material/indexDj";
    }

    /**
     * @param page 当前页
     * @param limit 每页总数
     * @param cusCode 供应商编码
     * @param invCode 料号
     * @param invDef 机种
     * @return
     */
    @RequestMapping("/baseList")
    @ResponseBody
    public LayTableR list(Integer page,Integer limit,String cusCode,String invCode,String invDef){
        List<String> objects = baseMaterialService.selectBaseMaterialAllGroupSet();
        IPage<BaseMaterial> list = baseMaterialService.getBaseMaterialList(page, limit, cusCode, invCode, invDef);
        if (!objects.isEmpty() && list.getTotal() > 0){
            for (BaseMaterial record : list.getRecords()) {
                if (objects.contains(record.getComponentId())) {
                    record.setLAY_CHECKED(true);
                }
            }
        }
        return LayTableR.result(0,list.getTotal(),list.getRecords());
    }

    @RequestMapping("/iosBaseList")
    @ResponseBody
    public LayTableR iosBaseList(Integer page,Integer limit,String cusCode,String invCode,String invDef){
        IPage<ReportDTO> reportList = djBaseMaterialService.getReportList(-1, -1, cusCode, invCode, invDef);
        List<ReportDTO> list = new ArrayList<>();
        for (ReportDTO record : reportList.getRecords()) {
            if (StringUtils.isNotEmpty(record.getMaterialType())){
                if (record.getMaterialType().equals("A") || record.getMaterialType().equals("B") || record.getMaterialType().equals("D")){
                    record.setMaterialType(MaterialTypeConstant.getMessage(record.getMaterialType()));
                }else {
                    //其他都是辅料
                    record.setMaterialType(MaterialTypeConstant.C.getMessage());
                }
                list.add(record);
            }
        }
        return LayTableR.result(0,list.size(),list);
    }

    @RequestMapping("/iosBaseListApi")
    @ResponseBody
    @ValidateJWT
    public LayTableR iosBaseListApi(Integer page,Integer limit,String cusCode,String invCode,String invDef){
        return iosBaseList(page, limit, cusCode, invCode, invDef);
    }
    /**
     * @param page 当前页
     * @param limit 每页总数
     * @param cusCode 供应商编码
     * @param invCode 料号
     * @param invDef 机种
     * @return
     */
    @RequestMapping("/djBaseList")
    @ResponseBody
    public LayTableR djList(Integer page,Integer limit,String cusCode,String invCode,String invDef){
        IPage<BaseMaterial> list = djBaseMaterialService.getBaseMaterialList(page, limit, cusCode, invCode, invDef);
        return LayTableR.result(0,list.getTotal(),list.getRecords());
    }

    @RequestMapping("/selectTableList")
    @ResponseBody
    public LayTableR selectTableList(Integer page,Integer limit,String djMaterial){
        Page<BaseMaterial> page1 = djBaseMaterialService.selectTableList(page,limit,djMaterial);
        return LayTableR.result(0,page1.getTotal(),page1.getRecords());
    }

    /**
     * @return
     */
    @RequestMapping("/getReport")
    @ResponseBody
    public LayTableR getReport(String bomId,String cusCode){
        if (StringUtils.isNotEmpty(bomId)){
            LayTableR.result(0,0,null);
        }
        List<BaseMaterial> list = baseMaterialService.getReport(bomId,cusCode);
        return LayTableR.result(0,list.size(),list);
    }

    @RequestMapping("/getReportNext")
    @ResponseBody
    public LayTableR getReportNext(String bomId,String cusCode){
        if (StringUtils.isNotEmpty(bomId)){
            LayTableR.result(0,0,null);
        }
        List<BaseMaterial> list = baseMaterialService.getReportNext(bomId,cusCode);
        return LayTableR.result(0,list.size(),list);
    }

    @RequestMapping("/getReportNextApi")
    @ResponseBody
    @ValidateJWT
    public LayTableR getReportNextApi(String bomId,String cusCode){
        if (StringUtils.isNotEmpty(bomId)){
            LayTableR.result(0,0,null);
        }
        List<BaseMaterial> list = baseMaterialService.getReportNext(bomId,cusCode);
        List<ReportDTO> reportDTOS = new ArrayList<>();
        for (BaseMaterial baseMaterial : list) {
            ReportDTO dto = new ReportDTO();
            dto.setBmb01(baseMaterial.getDjMaterial());
            dto.setIma021m(baseMaterial.getCusMaterial());
            dto.setIma02m(baseMaterial.getMaterialMrk());
            dto.setBmb02("1");
            dto.setBmb03("");
            dto.setIma021("");
            dto.setIma02("");
            dto.setBomId(baseMaterial.getBomId());
            dto.setParentId(baseMaterial.getParentBomId());
            dto.setQPA(baseMaterial.getBaseQty());
            dto.setMaterialType(MaterialTypeConstant.getMessage(baseMaterial.getClassType()));
            reportDTOS.add(dto);
        }
        list.clear();
        return LayTableR.result(0,reportDTOS.size(),reportDTOS);
    }

    @GetMapping("/getReportDow")
    @ResponseBody
    public void getInventoryDow(String str,String cusCode, HttpServletResponse response){
        String queryCriteriaStr = "【查询条件】 供应商编码：" + cusCode;
        List<TitleEntity> titleList=new ArrayList<>();
        titleList.add(new TitleEntity("0",null,"iosReport管理信息表",null));
        titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));

        titleList.add(new TitleEntity("2","1","主件料号(⼚商料号) ","Bmb01"));
        titleList.add(new TitleEntity("3","1","主件料号的规格栏位(纬创料号) ","Ima021m"));
        titleList.add(new TitleEntity("4","1","主件料号的品名或料号描述","Ima02m"));
        titleList.add(new TitleEntity("5","1","单身项次(内部版本管控)","Bmb02"));
        titleList.add(new TitleEntity("6","1","下阶料号(⼚商料号) ","Bmb03"));
        titleList.add(new TitleEntity("7","1","下阶料号规格栏位(纬创料号)","Ima021"));
        titleList.add(new TitleEntity("8","1","主件料号的品名或料号描述","Ima02"));
        titleList.add(new TitleEntity("9","1","下阶料号QPA(单位⽤量 ps/g)","QPA"));
        titleList.add(new TitleEntity("10","1","材料类型","MaterialType"));

        LayTableR layTableR = this.iosBaseList(-1, -1, cusCode, null, null);
        List<Object> data = (List<Object>) layTableR.get("data");
        try {
            ExcelTool excelTool = new ExcelTool("iosReport管理信息表",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("调整"+str+"iosReport管理信息表"+ com.xmb.wcapi.util.DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
            excelTool.exportExcel(titleData,data, response.getOutputStream(),true,true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody List<String> ids) {
        try {
            djBaseMaterialService.removeBatchByIds(ids);
        } catch (Exception e) {
            return R.error("系统异常");
        }
        return R.ok();
    }


    @RequestMapping("/listDetails")
    @ResponseBody
    public LayTableR listDetails(String bomId,String allId,String cusCode){
        if (StringUtils.isEmpty(bomId)){
            return LayTableR.result(0,0,null);
        }
        List<BaseMaterial> list1 = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(StringUtils.isNotEmpty(cusCode),BaseMaterial::getCusCode,cusCode)
                .eq(StringUtils.isNotEmpty(allId),BaseMaterial::getAllComponentId,allId)
                .eq(BaseMaterial::isChecked,true)
        );
        List<BaseMaterial> list = baseMaterialService.getBaseMaterialDetailsList(bomId,cusCode);
        if (!list1.isEmpty() && !list.isEmpty()){
            List<String> collect = list1.stream().map(BaseMaterial::getOpComponentId).collect(Collectors.toList());
            for (BaseMaterial material : list) {
                if (collect.contains(material.getOpComponentId())) {
                    material.setLAY_CHECKED(true);
                }
            }
        }
        return LayTableR.result(0,list.size(),list);
    }

    @RequestMapping("/saveBaseMaterial")
    @ResponseBody
    public R saveBaseMaterial(String list){
        List<BaseMaterial> toList = BeanUtil.parseObjToList(list, BaseMaterial.class);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<BaseMaterial> materials = toList.stream().filter(res -> res.getParentBomId().equals("0")).collect(Collectors.toList());
        if (!materials.isEmpty()){
            BaseMaterial baseMaterial1 = materials.get(0);
            baseMaterial1.setAllComponentId(baseMaterial1.getOpComponentId());
            baseMaterial1.setLevels(0);
            //先删除
            baseMaterialService.remove(Wrappers.lambdaUpdate(BaseMaterial.class).eq(BaseMaterial::getAllComponentId,baseMaterial1.getOpComponentId()));
            for (BaseMaterial baseMaterial : toList) {
                if (baseMaterial.getParentBomId().equals("0")){
                    baseMaterial.setLevels(0);
                }
                baseMaterial.setCusCode(baseMaterial1.getCusCode());
                baseMaterial.setCusName(baseMaterial1.getCusName());
                baseMaterial.setId(IdUtil.getSnowflakeNextIdStr());
                baseMaterial.setCreateUser(user.getId());
                baseMaterial.setCreateTime(new Date());
                baseMaterial.setAllComponentId(baseMaterial1.getOpComponentId());
            }
            //层级构建 查找出 顶级bom
            Map<String, List<BaseMaterial>> collect = toList.stream().collect(Collectors.groupingBy(BaseMaterial::getParentBomId));
            List<BaseMaterial> listAll = new ArrayList<>();
            listAll.add(baseMaterial1);
            List<BaseMaterial> baseMaterials = collect.get(baseMaterial1.getBomId());
            for (BaseMaterial baseMaterial : baseMaterials) {
                baseMaterial.setLevels(1);
                listAll.add(baseMaterial);
                if (StringUtils.isNotEmpty(baseMaterial.getBomId())){
                    getBaseMaterialBomLevelMap(baseMaterial.getBomId(),collect,listAll,1);
                }
            }
            return baseMaterialService.saveBaseMaterial(listAll,baseMaterial1);
        }
        return R.error("未勾选顶级dom");

    }

    public static void getBaseMaterialBomLevelMap(String bomId,Map<String, List<BaseMaterial>> collect,List<BaseMaterial> listAll,Integer leve){
        boolean mark = false;
        List<BaseMaterial> materials = collect.get(bomId);
        if (null != materials){
            for (BaseMaterial material : materials) {
                material.setLevels(leve);
                if (StringUtils.isNotEmpty(material.getBomId())){
                    bomId = material.getBomId();
                    mark = true;
                }
            }
            listAll.addAll(materials);
        }
        if (mark){
            leve = leve + 1;
            getBaseMaterialBomLevelMap(bomId, collect, listAll, leve);
        }
    }

}

